package com.sanji.sjmallutils;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.BuildConfig;
import android.support.v4.content.FileProvider;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallconfig.ConfigConts;

import java.io.File;

public class DownloadService extends Service {

    private DownloadManager dm;
    private long enqueue;
    private BroadcastReceiver receiver;
    private String apkName = "";
    private String apkUrl;
    private File apkFile = null;


    public DownloadService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Intent intent1 = new Intent(Intent.ACTION_VIEW);
                //判断是否是AndroidN以及更高的版本
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                    intent1.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(context, "com.sanji.sjmallapp.fileprovider",new File(apkFile.getPath() + File.separator + apkName));
                    intent1.setDataAndType(contentUri,"application/vnd.android.package-archive");
                }else{
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent1.setDataAndType(Uri.fromFile(new File(apkFile.getPath() + File.separator + apkName)),
                            "application/vnd.android.package-archive");

                }
                startActivity(intent1);
                stopSelf();
            }
        };

        apkUrl = intent.getStringExtra("apkUrl");
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        startDownload();
        return Service.START_STICKY;
    }

    private void startDownload(){
        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
        request.setMimeType("application/vnd.android.package-archive");
        apkName = "三际商城 " + Tools.getCurrentTime() + ".apk";
        apkFile = new File(SDCardUtil.getApkPath());
        if (apkFile != null && apkFile.exists() && apkFile.isDirectory()){
            for (File item : apkFile.listFiles()){
                item.delete();
            }
        }else{
            apkFile.mkdirs();
        }
        if(SDCardUtil.checkSdCard()){
            //下载到SD卡
            request.setDestinationInExternalPublicDir(SDCardUtil.FILEAPK,apkName);
        }else{
            //下载到内置目录
            request.setDestinationInExternalFilesDir(MallApplication.getApplication(),SDCardUtil.FILEAPK,apkName);
        }
        enqueue = dm.enqueue(request);
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}
